package cc.sheji.Service;


import cc.sheji.domain.CoinLog;
import cc.sheji.domain.CoinLogQueryCriteria;
import cc.sheji.domain.PayLog;
import cc.sheji.domain.PayLogQueryCriteria;
import cc.sheji.reposity.CoinLogRepository;
import cc.sheji.util.QueryHelp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.BiConsumer;

@Service
public class CoinLogService {

    @Autowired
    CoinLogRepository coinLogRepository;


    public CoinLog create(CoinLog entity) {
        entity.setId(null);
        coinLogRepository.save(entity);
        return entity;
    }

    public CoinLog get(Long id) throws InterruptedException {
        CoinLog entity = coinLogRepository.findById(id).get();
        return entity;
    }

    public CoinLog update(CoinLog entity) {
        entity = coinLogRepository.save(entity);
        return entity;
    }


    public List<CoinLog> list(CoinLogQueryCriteria criteria, Pageable pageable) {
        Sort order = Sort.by(Sort.Direction.ASC, "createTime");
        order = Sort.by(Sort.Direction.DESC, "createTime");
        pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), order);
        Page<CoinLog> page = coinLogRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return page.getContent();
    }

    public Object getAll(CoinLogQueryCriteria criteria) {

        DateFormat format=new SimpleDateFormat("yyyy-MM");
        List<CoinLog> all = coinLogRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        LinkedHashMap<String,List<CoinLog>> map=new LinkedHashMap<>();
        for(int i=0;i<all.size();i++){
            CoinLog payLog = all.get(i);
            String date=format.format(payLog.getCreateTime());
            List<CoinLog> list =map.get(date);
            if(list==null){
                list=new ArrayList<>();
                map.put(date,list);
            }
            list.add(payLog);
        }
        List returnData=new ArrayList();
        map.forEach(new BiConsumer<String, List<CoinLog>>() {
            @Override
            public void accept(String s, List<CoinLog> payLogs) {
                Map item=new HashMap();
                item.put("key",s);
                item.put("value",payLogs);
                returnData.add(item);
            }
        });
        return returnData;
    }
}
